let _Vue = null
export default class VueRouter {
  constructor(options) {
    this.routes = options.routes
    this.keyMap = {}
    this.currentRoute = _Vue.observable({
      route: '/#'
    })
    this.init()
  }
  static install(Vue) {
    // 判断插件是否已加载过
    if (VueRouter.install.isInstalled) return
    VueRouter.install.isInstalled = true
    // 获取 Vue 构造函数
    _Vue = Vue
    // 注册插件到 Vue 的构造函数上
    _Vue.mixin({
      // 这时候的 this 指向当前 Vue 实例
      beforeCreate() {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
          _Vue.prototype.$router.init()
        }
      }
    })
  }
  init() {
    this.initMap(this.routes)
    this.initComponent()
    this.initEvent()
  }
  initMap(routes) {
    routes.forEach(route => {
      this.keyMap[route.path] = route.component
    })
  }
  initComponent() {
    const self = this
    _Vue.component('router-link', {
      props: {
        to: String
      },
      render(h) {
        return h('a', {
          attrs: {
            href: this.to,
          },
          on: {
            click: this.handleClick
          }
        }, [this.$slots.default])
      },
      methods: {
        handleClick(e) {
          self.currentRoute.route = `/#${this.to}`
          window.location.hash = self.currentRoute.route.replace('/#', '')
          e.preventDefault()
        }
      }
    })
    _Vue.component('router-view', {
      render(h) {
        self.currentRoute.route = window.location.hash.replace('#', '')
        return h(self.keyMap[self.currentRoute.route])
      }
    })
  }
  initEvent() {
    window.addEventListener('hashchange', () => {
      this.currentRoute.route = window.location.hash
    })
  }
}